package com.older.wptsb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.older.wptsb.domain.dto.*;
import com.older.wptsb.domain.po.Elder;
import com.older.wptsb.domain.po.User;
import com.older.wptsb.domain.vo.UserLoginVO;
import com.older.wptsb.exception.LoginException;
import com.older.wptsb.exception.LoginRegisterException;
import com.older.wptsb.mapper.CommunityElderMapper;
import com.older.wptsb.mapper.UserMapper;
import com.older.wptsb.service.UserService;
import com.older.wptsb.util.JwtUtil;
import com.older.wptsb.util.PasswordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private CommunityElderMapper communityElderMapper;

    //用户登录
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        String userName = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", userName));
        if (user != null && PasswordUtil.matches(password, user.getPassword())) {
            // 检查是否需要自动绑定
            UserLoginVO userLoginVO = checkAndBindUser(user);

            String token = JwtUtil.generateToken(user.getUserId(), user.getUsername(),user.getRoleType());
            // 构造返回结果
            userLoginVO.setToken(token);
            userLoginVO.setUserId(String.valueOf(user.getUserId()));
            userLoginVO.setName(user.getRealName());
            return userLoginVO;
        }
        throw new LoginException("用户名或密码错误");
    }

    private UserLoginVO checkAndBindUser(User user) {
        UserLoginVO loginVO = new UserLoginVO();
        loginVO.setNeedBindElder(false);
        loginVO.setNeedBindCommunity(false);

        // 老人账号自动绑定社区
        if ("elder".equals(user.getRoleType()) && user.getCommunityId() == null) {
            Elder elder = communityElderMapper.selectOne(
                new QueryWrapper<Elder>().eq("name", user.getRealName()));
            System.out.println(elder);
            if (elder != null && elder.getCommunityId() != null) {
                user.setCommunityId(Integer.valueOf(elder.getCommunityId()));
                System.out.println(user);
                userMapper.updateByUserId(user);
            } else {
                // 老人信息未找到或未分配社区，需要在前端提示
                loginVO.setNeedBindCommunity(true);
            }
        }
        // 家属账号检查是否绑定老人
        else if ("family".equals(user.getRoleType())) {
            // 检查是否已经绑定了老人
            int bindingCount = userMapper.countElderBindings(user.getUserId().longValue());
            if (bindingCount == 0) {
                // 如果没有绑定老人，设置标记让前端跳转绑定页面
                loginVO.setNeedBindElder(true);
            }
        }

        return loginVO;
    }

    //用户注册
    @Override
    public void register(UserRegisterDTO userRegisterDTO) {
        User user = userMapper .selectOne(new QueryWrapper<User>().eq("username", userRegisterDTO.getUsername()));
        if (user == null) {
            LocalDateTime now = LocalDateTime.now();

            // 格式化时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);
            String encryptedPassword = PasswordUtil.encode(userRegisterDTO.getPassword());
            userMapper.insert(User.builder()
                    .username(userRegisterDTO.getUsername())
                    .password(encryptedPassword)
                    .phone(userRegisterDTO.getPhone())
                    .realName(userRegisterDTO.getRealName())
                    .roleType(userRegisterDTO.getRoleType())
                    .createTime(formattedNow)
                    .build());
            log.info("用户注册成功");
        }
        else {
            log.info("用户已存在");
            throw new LoginRegisterException("用户名已存在");
        }
    }
    //忘记密码
    @Override
    public void back(UserBackDTO userBackDTO) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", userBackDTO.getUsername()));
        if (user == null){
            log.info("用户不存在");
            throw new LoginException("用户不存在");
        }
        else {
            if (!Objects.equals(user.getPhone(), userBackDTO.getPhone())){
                throw new LoginException("错误");
            }
            if (!Objects.equals(user.getRealName(), userBackDTO.getRealName())){
                throw new LoginException("错误");
            }
        }
    }
    //修改密码
    @Override
    public void backPassword(UpdatePasswordDTO updatePasswordDTO) {
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", updatePasswordDTO.getUsername()));
        if (user == null) {
            throw new LoginException("用户不存在");
        }
        String encryptedPassword = PasswordUtil.encode(updatePasswordDTO.getPassword());
        user.setPassword(encryptedPassword);
        userMapper.updateByUserId(user);
    }

    @Override
    public void register1(UserCommunityRegisterDTO userCommunityRegisterDTO) {
        User user = userMapper .selectOne(new QueryWrapper<User>().eq("username", userCommunityRegisterDTO.getUsername()));
        if (user == null) {
            LocalDateTime now = LocalDateTime.now();

            // 格式化时间
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String formattedNow = now.format(formatter);
            String encryptedPassword = PasswordUtil.encode(userCommunityRegisterDTO.getPassword());
            userMapper.insert(User.builder()
                    .username(userCommunityRegisterDTO.getUsername())
                    .password(encryptedPassword)
                    .phone(userCommunityRegisterDTO.getPhone())
                    .communityId(userCommunityRegisterDTO.getCommunityId())
                    .realName(userCommunityRegisterDTO.getRealName())
                    .roleType(userCommunityRegisterDTO.getRoleType())
                    .createTime(formattedNow)
                    .build());
            log.info("用户注册成功");
        }
        else {
            log.info("用户已存在");
            throw new LoginRegisterException("用户名已存在");
        }
    }
    @Override
    public void updateById(UserDTO userDTO) {
        User user = new User();
        user.setUserId(userDTO.getUserId());
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setPhone(userDTO.getPhone());
        user.setRealName(userDTO.getRealName());
        user.setCommunityId(userDTO.getCommunityId());
        user.setRoleType(userDTO.getRoleType());
        //userMapper.updateByUserId(user);
    }


}
